from PySide6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                              QPushButton, QLabel, QTextEdit, QFileDialog, 
                              QProgressBar, QDialog)
from contract_renamer.utils.worker import Worker
from contract_renamer.gui.api_config_dialog import APIConfigDialog
from contract_renamer.config import load_config, save_config
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QPalette
import darkdetect
from pathlib import Path
from contract_renamer.resources.icons import get_app_icon

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.worker = None  # 初始化 worker 属性
        self.setWindowIcon(get_app_icon())  # 设置窗口图标
        self.init_ui()
        self.load_last_dirs()  # 加载上次使用的目录
        self.setup_theme()
        
        # 设置定时器检查系统主题变化
        self.theme_timer = QTimer(self)
        self.theme_timer.timeout.connect(self.check_system_theme)
        self.theme_timer.start(5000)  # 每5秒检查一次
        self.current_theme = None
        self.is_theme_auto = True  # 改名：theme_auto -> is_theme_auto
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("合同文件重命名工具")
        self.setMinimumSize(800, 600)
        
        # 创建主窗口部件和布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        layout = QVBoxLayout(main_widget)
        
        # 输入目录选择
        input_layout = QHBoxLayout()
        self.input_label = QLabel("输入目录：")
        self.input_path = QLabel("未选择")
        self.input_button = QPushButton("选择目录")
        self.input_button.clicked.connect(self.select_input_dir)
        input_layout.addWidget(self.input_label)
        input_layout.addWidget(self.input_path, 1)
        input_layout.addWidget(self.input_button)
        layout.addLayout(input_layout)
        
        # 输出目录选择
        output_layout = QHBoxLayout()
        self.output_label = QLabel("输出目录：")
        self.output_path = QLabel("未选择")
        self.output_button = QPushButton("选择目录")
        self.output_button.clicked.connect(self.select_output_dir)
        output_layout.addWidget(self.output_label)
        output_layout.addWidget(self.output_path, 1)
        output_layout.addWidget(self.output_button)
        layout.addLayout(output_layout)
        
        # 进度条
        self.progress_bar = QProgressBar()
        layout.addWidget(self.progress_bar)
        
        # 日志显示区域
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        layout.addWidget(self.log_text)
        
        # 添加配置状态显示
        status_layout = QHBoxLayout()
        self.api_status_label = QLabel()
        self.update_api_status()
        
        # 创建主题按钮组
        theme_group = QHBoxLayout()
        self.theme_auto_btn = QPushButton("自动主题")  # 改名：theme_auto -> theme_auto_btn
        self.theme_light_btn = QPushButton("浅色主题")  # 改名：theme_light -> theme_light_btn
        self.theme_dark_btn = QPushButton("深色主题")   # 改名：theme_dark -> theme_dark_btn
        
        # 设置主题属性，用于样式表
        for btn in [self.theme_auto_btn, self.theme_light_btn, self.theme_dark_btn]:
            btn.setProperty("theme", True)
            btn.setFixedWidth(80)
            btn.setFixedHeight(30)
            theme_group.addWidget(btn)
        
        # 连接信号
        self.theme_auto_btn.clicked.connect(lambda: self.change_theme('auto'))
        self.theme_light_btn.clicked.connect(lambda: self.change_theme('light'))
        self.theme_dark_btn.clicked.connect(lambda: self.change_theme('dark'))
        
        status_layout.addWidget(self.api_status_label)
        status_layout.addStretch()
        status_layout.addLayout(theme_group)
        layout.addLayout(status_layout)
        
        # 操作按钮
        button_layout = QHBoxLayout()
        self.classify_button = QPushButton("按文档类型分类")
        self.classify_button.clicked.connect(self.start_classifying)
        self.classify_button.setEnabled(False)
        self.start_button = QPushButton("识别并分类")
        self.start_button.clicked.connect(self.start_processing)
        self.start_button.setEnabled(False)
        self.config_button = QPushButton("API配置")
        self.config_button.clicked.connect(self.show_api_config)
        self.stop_button = QPushButton("停止处理")
        self.stop_button.setObjectName("stopButton")  # 用于QSS样式
        self.stop_button.clicked.connect(self.stop_processing)
        self.stop_button.setEnabled(False)  # 初始状态禁用
        button_layout.addWidget(self.classify_button)
        button_layout.addWidget(self.start_button)
        button_layout.addWidget(self.config_button)
        button_layout.addWidget(self.stop_button)
        layout.addLayout(button_layout)
        
        self.input_dir = None
        self.output_dir = None
        
    def load_last_dirs(self):
        """加载上次使用的目录"""
        config = load_config()
        last_dirs = config.get('last_dirs', {})
        
        # 加载输入目录
        input_dir = last_dirs.get('input', '')
        if input_dir and Path(input_dir).exists():
            self.input_dir = input_dir
            self.input_path.setText(input_dir)
        
        # 加载输出目录
        output_dir = last_dirs.get('output', '')
        if output_dir and Path(output_dir).exists():
            self.output_dir = output_dir
            self.output_path.setText(output_dir)
        
        # 检查是否可以启用开始按钮
        self.check_start_button()
        
    def save_last_dirs(self):
        """保存当前使用的目录"""
        config = load_config()
        config['last_dirs'] = {
            'input': self.input_dir or '',
            'output': self.output_dir or ''
        }
        save_config(config)
        
    def select_input_dir(self):
        dir_path = QFileDialog.getExistingDirectory(
            self, 
            "选择输入目录",
            self.input_dir or ""  # 使用上次的目录作为起始目录
        )
        if dir_path:
            self.input_dir = dir_path
            self.input_path.setText(dir_path)
            self.check_start_button()
            self.save_last_dirs()  # 保存目录设置
            
    def select_output_dir(self):
        dir_path = QFileDialog.getExistingDirectory(
            self, 
            "选择输出目录",
            self.output_dir or ""  # 使用上次的目录作为起始目录
        )
        if dir_path:
            self.output_dir = dir_path
            self.output_path.setText(dir_path)
            self.check_start_button()
            self.save_last_dirs()  # 保存目录设置
            
    def check_start_button(self):
        """检查是否可以启用开始按钮"""
        has_dirs = bool(self.input_dir and self.output_dir)
        self.classify_button.setEnabled(has_dirs)
        # OCR按钮需要检查API配置
        self.start_button.setEnabled(has_dirs and self.check_api_config())
        
    def _prepare_processing(self):
        """准备��理前的通用操作"""
        self.start_button.setEnabled(False)
        self.classify_button.setEnabled(False)
        self.input_button.setEnabled(False)
        self.output_button.setEnabled(False)
        self.progress_bar.setValue(0)
        self.log_text.clear()
        
    def start_processing(self):
        """开始处理文件"""
        self._prepare_processing()
        self.worker = Worker(self.input_dir, self.output_dir, mode="ocr")  # 先实例化 Worker
        self.worker.should_stop = False  # 然后设置 should_stop
        self._connect_worker()
        self.worker.start()
        self.stop_button.setEnabled(True)  # 启用停止按钮
        self.start_button.setEnabled(False)  # 禁用处理按钮
        
    def start_classifying(self):
        self._prepare_processing()
        self.worker = Worker(self.input_dir, self.output_dir, mode="filename")  # 先实例化 Worker
        self.worker.should_stop = False  # 然后设置 should_stop
        self._connect_worker()
        self.worker.start()
        
    def _connect_worker(self):
        """连接工作线程的信号"""
        self.worker.progress_updated.connect(self.update_progress)
        self.worker.status_updated.connect(self.update_log)
        self.worker.finished.connect(self.processing_finished)
        
    def update_progress(self, value):
        self.progress_bar.setValue(value)
        
    def update_log(self, text):
        self.log_text.append(text)
        
    def processing_finished(self):
        """处理完成后的回调"""
        self.stop_button.setEnabled(False)
        self.start_button.setEnabled(True)
        self.classify_button.setEnabled(True)
        self.input_button.setEnabled(True)
        self.output_button.setEnabled(True)
        
    def show_api_config(self):
        """显示API配置对话框"""
        dialog = APIConfigDialog(self)
        if dialog.exec() == QDialog.Accepted:
            # 配置已保存，更新状态显示和按钮状态
            self.update_api_status()
            self.check_start_button()
        
    def check_api_config(self):
        """检查API配置是否完整"""
        config = load_config()
        baidu_config = config.get('baidu_ocr', {})
        return all(baidu_config.get(key) for key in ['app_id', 'api_key', 'secret_key'])
        
    def update_api_status(self):
        """更新API配置状态显示"""
        if self.check_api_config():
            self.api_status_label.setText("API状态：配置")
            self.api_status_label.setStyleSheet("color: green")
        else:
            self.api_status_label.setText("API状态：未配置")
            self.api_status_label.setStyleSheet("color: red")
        
    def stop_processing(self):
        """停止处理文件"""
        if self.worker:
            self.worker.should_stop = True
            self.stop_button.setEnabled(False)
            self.log_text.append("正在停止处理...")
        
    def setup_theme(self):
        """设置主题"""
        theme = self.get_system_theme()
        self.apply_theme(theme)
        self.current_theme = theme

    def get_system_theme(self):
        """获取系统主题"""
        return 'dark' if darkdetect.isDark() else 'light'

    def apply_theme(self, theme):
        """应用主题"""
        style_dir = Path(__file__).parent.parent / 'styles'
        theme_file = style_dir / f'{theme}_theme.qss'
        
        if theme_file.exists():
            with open(theme_file, 'r', encoding='utf-8') as f:
                self.setStyleSheet(f.read())

    def change_theme(self, theme_mode):
        """切换主题模式"""
        if theme_mode == 'auto':
            self.is_theme_auto = True
            theme = self.get_system_theme()
        else:
            self.is_theme_auto = False
            theme = theme_mode
            
        self.apply_theme(theme)
        self.current_theme = theme
        
        # 更新按钮状态
        self.theme_auto_btn.setEnabled(not (theme_mode == 'auto'))
        self.theme_light_btn.setEnabled(not (theme_mode == 'light' and not self.is_theme_auto))
        self.theme_dark_btn.setEnabled(not (theme_mode == 'dark' and not self.is_theme_auto))

    def check_system_theme(self):
        """检查系统主题是否改变"""
        if self.is_theme_auto:  # 使用新的变量名
            current_theme = self.get_system_theme()
            if current_theme != self.current_theme:
                self.apply_theme(current_theme)
                self.current_theme = current_theme